interface LogData {
  level: 'info' | 'warn' | 'error';
  message: string;
  timestamp: number;
  data?: any;
  user?: string;
  path?: string;
}

class Logger {
  private logs: LogData[] = [];
  private maxLogs: number = 100;

  constructor() {
    window.addEventListener('error', this.handleError.bind(this));
    window.addEventListener('unhandledrejection', this.handlePromiseError.bind(this));
  }

  private handleError(event: ErrorEvent) {
    this.error(event.message, {
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
      stack: event.error?.stack,
    });
  }

  private handlePromiseError(event: PromiseRejectionEvent) {
    this.error('Unhandled Promise Rejection', {
      reason: event.reason,
    });
  }

  info(message: string, data?: any) {
    this.addLog('info', message, data);
  }

  warn(message: string, data?: any) {
    this.addLog('warn', message, data);
  }

  error(message: string, data?: any) {
    this.addLog('error', message, data);
  }

  private addLog(level: LogData['level'], message: string, data?: any) {
    const log: LogData = {
      level,
      message,
      timestamp: Date.now(),
      data,
      user: localStorage.get('auth_user')?.username,
      path: window.location.pathname,
    };

    this.logs.unshift(log);
    if (this.logs.length > this.maxLogs) {
      this.logs.pop();
    }

    // TODO: 发送日志到服务器
    console[level](message, data);
  }

  getLogs() {
    return this.logs;
  }
}

export const logger = new Logger();